package com.linkgie.galaxyframework.utils.bean;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

public final class BeanFields<T> {

    private BeanFieldSelector<T> fieldSelector;

    private Set<String> selectedFieldNames = new LinkedHashSet<>();

    private BeanFields(BeanFieldSelector<T> fieldSelector) {
        this.fieldSelector = fieldSelector;
    }

    public static <T> BeanFields<T> of(Class<T> beanType) {
        BeanFieldSelector<T> fieldSelector = BeanFieldSelector.resolve(beanType);
        return new BeanFields<>(fieldSelector);
    }

    public BeanFields<T> select(FieldSelect<T> selectFunction) {
        String fieldName = fieldSelector.select(selectFunction);
        selectedFieldNames.add(fieldName);
        return this;
    }

    public Set<String> fieldNames(){
        return Collections.unmodifiableSet(new LinkedHashSet<>(selectedFieldNames));
    }

    public FieldSelection<T> selection(){
         InnerFieldSelection<T> selection = new InnerFieldSelection<>(fieldSelector.getType(), fieldNames());

         return selection;
    }

    private static class InnerFieldSelection<B> implements FieldSelection<B> {

        private final Set<String> fieldNames;

        private final Class<B> beanType;

        private InnerFieldSelection(Class<B> beanType, Set<String> fieldNames){
            this.beanType = beanType;
            this.fieldNames = fieldNames;
        }

        @Override
        public Class<B> getBeanType() {
            return beanType;
        }

        @Override
        public Set<String> getFieldNames() {
            return fieldNames;
        }
    
        
    }
}
